package larrys.pomodoro.controller.pages;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import larrys.pomodoro.Constant;
import larrys.pomodoro.domain.entity.Activity;
import larrys.pomodoro.domain.entity.PomodoroUser;
import larrys.pomodoro.domain.entity.Round;
import larrys.pomodoro.domain.service.ActivityService;
import larrys.pomodoro.domain.service.RoundService;
import larrys.pomodoro.form.ActivityFormBean;
import larrys.pomodoro.util.SecurityUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ActivityController {

	private static Log logger = LogFactory.getLog(ActivityController.class);

	@Autowired
	private MessageSource messages;

	@Autowired
	private Validator validator;

	@Autowired
	private ActivityService activityService;

	@Autowired
	private RoundService roundService;

	private void setActiviyModelActive(Model model) {
		model.addAttribute(Constant.ACTIVIE_ATTRNAME, "My Activity");
	}

	private void setActivityModels(Model model) {
		PomodoroUser user = SecurityUtils.getCurrentUser();
		model.addAttribute("activities",
				activityService.getAllActivitiesByUserId(user.getId()));
		Round runningRound = roundService.getRunningRound(user.getId());
		model.addAttribute("hasRunningRound", runningRound != null);
		model.addAttribute(Constant.ACTIVIE_ATTRNAME, "My Activity");
	}

	@RequestMapping(value = "/activity", method = RequestMethod.GET)
	public String activiyGet(Model model) {
		setActiviyModelActive(model);
		setActivityModels(model);
		return "activity/activity";
	}

	@RequestMapping(value = "/createactivity")
	public String createActivityGet(Model model) {
		setActiviyModelActive(model);
		return "activity/createactivity";
	}

	@RequestMapping(value = "/activity", method = RequestMethod.POST)
	public String activityPost(@RequestParam("name") String[] names,
			@RequestParam("description") String[] descs,
			@RequestParam("planDate") String[] planDates,
			@RequestParam("priority") int[] priorities,
			@RequestParam("estimation") int[] estimations, Model model,
			Locale locale) {
		setActiviyModelActive(model);
		PomodoroUser user = SecurityUtils.getCurrentUser();
		List<Activity> activities = new ArrayList<Activity>();
		boolean invalid = false;
		for (int i = 0; i < names.length; i++) {
			ActivityFormBean activityBean = new ActivityFormBean();
			activityBean.setName(names[i]);
			if (descs != null && i < descs.length) {
				activityBean.setDescription(descs[i]);
			}
			if (planDates != null && i < planDates.length) {
				activityBean.setPlanDate(planDates[i]);
			}
			if (priorities != null && i < priorities.length) {
				activityBean.setPriority(priorities[i]);
			}
			if (estimations != null && i < estimations.length) {
				activityBean.setEstimation(estimations[i]);
			}

			for (ConstraintViolation<ActivityFormBean> violation : validator
					.validate(activityBean)) {
				invalid = true;
				model.addAttribute(violation.getPropertyPath().toString()
						+ Constant.FORM_ERROR_SUFFIX, violation.getMessage());
			}
			boolean permanentFalse = false, finishedFalse = false;
			Activity activity = new Activity(0, activityBean.getName(),
					user.getId(), permanentFalse, finishedFalse);
			activity.setDescription(activityBean.getDescription());
			activity.setEstimation(activityBean.getEstimation());
			try {
				activity.setPlanDate(activityBean.getPlanDateByDate());
			} catch (ParseException e) {
				invalid = true;
				logger.error("Exception threw while parsing plan date:"
						+ activityBean.getPlanDate(), e);
				model.addAttribute("plandate" + Constant.FORM_ERROR_SUFFIX,
						messages.getMessage(
								"message_error_activityplandateformat", null,
								locale));
			}
			activity.setPriority(activityBean.getPriority());
			activities.add(activity);
		}

		if (!invalid) {
			activityService.AddActivies(activities);
		}
		setActivityModels(model);
		return "activity/activity";
	}

	@RequestMapping(value = "/deleteactivity", method = RequestMethod.GET)
	public String deleteActivity(Model model,
			@RequestParam("activity_id") long activityId) {
		activityService.deleteActivity(activityId);
		setActivityModels(model);
		return "redirect:/pages/activity";
	}

	@RequestMapping("/finishactivity")
	public String finishActivity(Model model,
			@RequestParam("activity_id") long activityId) {
		activityService.finishActivity(activityId);
		model.addAttribute("activityId", activityId);
		return "activity/activitycomment";
	}

	@RequestMapping("/activitycomment")
	public String activityComment(@RequestParam("activity_id") long activityId,
			@RequestParam(value = "comment", required = true) String comment)
			throws IOException {

		logger.debug("Trying to add comment to Activity[id:" + activityId + "]");
		if (comment != null && !comment.isEmpty()) {
			activityService.addActivityComment(activityId, comment);
		}
		logger.debug("Finished add comment to Activity[id:" + activityId + "]");
		return "redirect:/pages/activity";
	}

}
